About 1537 letters

About 8 minutes

#Python process creation

In modern computer systems, multiple program instances can run simultaneously. For example, a user can work with Word while listening to music with a media player.

A running program instance is called a process. It is the basic unit of resource allocation by the operating system. Each process has its own independent memory space and system resources.

In Python, you create processes using the Process class from the multiprocessing module:

p = Process(target=entry_function, args=argument_list)

For example:

from multiprocessing import Process import os import time # Entry function for the process def worker(name): for _ in range(3): print(f'{os.getpid()}: My name is {name}') time.sleep(1) # Process blocks for 1 second if __name__ == '__main__': p1 = Process(target=worker, args=('worker1',)) # Create process p2 = Process(target=worker, args=('worker2',)) p1.start() # Start processes p2.start() p1.join() # Wait for processes to finish p2.join()

Output:

45352: My name is worker1 94204: My name is worker2 45352: My name is worker1 94204: My name is worker2 45352: My name is worker1 94204: My name is worker2

Notes:

  • The main process must check __name__ == '__main__' because Python creates child processes by re-importing the module. Without this check, infinite recursive process creation will occur.
  • Process scheduling order is not guaranteed, so the output order is unpredictable.

Created in 5/15/2025

Updated in 5/21/2025